package com.example.woke;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.http.HttpMethods;
import com.kspay.DateUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.bugly.beta.Beta;
import com.woke.data.Datas_event2;
import com.woke.diyview.BaseViewPager;
import com.woke.fragment.NearbyFragment;
import com.woke.fragment.TabHomeFragment;
import com.woke.fragment.UserFragment;
import com.woke.jpush.ExampleUtil;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {

	private static final int READ_AND_WRITE_STORE = 8;
	public static boolean isForeground = false;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.woke.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	private BaseViewPager mViewPager;
	private TabLayout mTabLayout;
	private String[] mTabTitle = new String[]{"首页", "好友", "我"};
	private int[] mTabIndicatorImg = new int[]{R.drawable.tab_home_selector, R.drawable.tab_friends_selector, R.drawable.tab_mine_selector};

	private MessageReceiver mMessageReceiver;
	private boolean isExit;
	private SharedPreferences sharep;
	private String stringExtra = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_main);
		Log.e("Util.sHA1)",Util.sHA1(MainActivity.this));
		String strin=getIntent ().getStringExtra ("deadToLive");// 极光推送 启动app
		String chenkUp=getIntent ().getStringExtra ("chenkUp");// 极光推送 启动app
		if(strin==null){
		}else if (strin.equals("deadToLive")){
			Intent i = new Intent(MainActivity.this,MyinfoActivity.class);
			startActivity(i);
		}
		if(chenkUp==null){
		}else if (chenkUp.equals("chenkUp")){
			Beta.checkUpgrade (); // 检查更新
		}
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder ().permitAll ()
					.build ();
			StrictMode.setThreadPolicy (policy);
		}

//		ShareSDK.initSDK (this);

		application = (MyApp) getApplication ();
		sharep = getSharedPreferences ("loaduser", Context.MODE_PRIVATE);
		stringExtra = "" + getIntent ().getStringExtra ("sdsdsf");

		initTab ();
		init ();
		registerMessageReceiver ();
		setAlias ();
		String timess1 = DateUtil.getTimess1 ();
		Log.e (timess1, timess1);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			methodRequiresTwoPermission ();
		}
		String registrationID = JPushInterface.getRegistrationID (MainActivity.this);
		application.setregid (registrationID);
		Log.e ("registrationID", "哈哈" + registrationID);
		String name_load = sharep.getString ("load", "not");
		if (name_load.equals ("load")) {
//			Beta.checkUpgrade ();
			uploadFile ();
		} else {
			Log.e ("not", "not");
		}

	}

	//    public void onEventMainThread(Datas_event2 event) {
//    	
//    }
	private static String servifee = "f";

	public String uploadFile() {
		sharep = getSharedPreferences ("loaduser", Context.MODE_PRIVATE);
//		application = (MyApp) getApplication();
		String regId = JPushInterface.getRegistrationID (this);
		final String name = sharep.getString ("name", "");
		final String password = sharep.getString ("password", "");

		AsyncHttpClient ahc = new AsyncHttpClient ();
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "login");
		params.put ("username", name);
		params.put ("password", password);
		params.put ("registerid", regId);
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject jsonObject = response.getJSONObject ("data");
						String string = jsonObject.getString ("data");
						Gson gson = new Gson ();
						Datas_load datas_load = gson.fromJson (string, Datas_load.class);
						MyApp myApp = (MyApp) getApplication ();
						myApp.setDatas_load (datas_load);
						Datas_event2 evens = new Datas_event2 ();
						evens.str1 = "load_suess";
						EventBus.getDefault ().post (evens);
						Editor edit = sharep.edit ();
						edit.putString ("name", name);
						edit.putString ("password", password);
						edit.commit ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
			}

			@Override
			public void onStart() {
				super.onStart ();
			}

			@Override
			public void onFinish() {
				super.onFinish ();
			}
		});
		return servifee;

	}


	private void setAlias() {
		mHandler.sendMessage (mHandler.obtainMessage (MSG_SET_ALIAS));
	}
	private static final int MSG_SET_ALIAS = 1001;
	private final Handler mHandler = new Handler () {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage (msg);
			isExit = false;
			switch (msg.what) {
				case MSG_SET_ALIAS:
					JPushInterface.setAlias (getApplicationContext (),
							JPushInterface.getRegistrationID(getApplicationContext ()),
							null);
					break;
				default:
			}
		}
	};
	private MyApp application;

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals (intent.getAction ())) {
				String messge = intent.getStringExtra (KEY_MESSAGE);
				String extras = intent.getStringExtra (KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder ();
				showMsg.append (KEY_MESSAGE + " : " + messge + "\n");
				if (! ExampleUtil.isEmpty (extras)) {
					showMsg.append (KEY_EXTRAS + " : " + extras + "\n");
				}
				setCostomMsg (showMsg.toString ());
			}
		}
	}

	private void setCostomMsg(String msg) {

	}

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver ();
		IntentFilter filter = new IntentFilter ();
		filter.setPriority (IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction (MESSAGE_RECEIVED_ACTION);
		registerReceiver (mMessageReceiver, filter);
	}

	private void init() {
		JPushInterface.init (getApplicationContext ());

	}

	@Override
	protected void onResume() {
		JPushInterface.onResume (this);
		isForeground = true;
		setStyleCustom ();
		super.onResume ();
	}

	@Override
	protected void onPause() {
		JPushInterface.onPause (this);
		isForeground = false;
		super.onPause ();
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver (mMessageReceiver);

		EventBus.getDefault ().unregister (this);
		super.onDestroy ();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getAction ()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_UP:

				break;
			default:
				break;
		}
		return super.dispatchTouchEvent (ev);
	}


	/**
	 * ����֪ͨ����ʽ - ����֪ͨ��Layout
	 */
	private void setStyleCustom() {
		CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder (MainActivity.this, R.layout.customer_notitfication_layout, R.id.imageView1, R.id.textView1, R.id.textView2);
		builder.layoutIconDrawable = R.mipmap.icn__launch_oem;
		builder.developerArg0 = "developerArg2";
		JPushInterface.setPushNotificationBuilder (2, builder);
//		Toast.makeText(MainActivity.this,"Custom Builder - 2", Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit ();
			return false;
		} else {
			return super.onKeyDown (keyCode, event);
		}

	}

	public void exit() {
		if (! isExit) {
			isExit = true;
			Toast.makeText (getApplicationContext (), "再按一次退出程序", Toast.LENGTH_SHORT).show ();
			mHandler.sendEmptyMessageDelayed (0, 2000);
		} else {
			Editor edit = sharep.edit ();
			edit.putString ("load", "not");
			edit.commit ();
			Intent intent = new Intent (Intent.ACTION_MAIN);
			intent.addCategory (Intent.CATEGORY_HOME);
			startActivity (intent);
			this.onDestroy ();
			System.exit (0);
		}
	}

//	Handler mHandler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			super.handleMessage(msg);
//			isExit = false;
//		}
//	};

	private void initTab() {
		mViewPager = (BaseViewPager) findViewById (R.id.mainViewPager);
		mTabLayout = (TabLayout) findViewById (R.id.mainTablayout);

		HomePagerFragmentAdapter mPagerFragmentAdapter = new HomePagerFragmentAdapter (getSupportFragmentManager ());
		mViewPager.setAdapter (mPagerFragmentAdapter);
		mViewPager.setOffscreenPageLimit (3);

		for (int i = 0; i < mTabTitle.length; i++) {
			mTabLayout.addTab (mTabLayout.newTab ()
					.setCustomView (getTabItemCustonView (mTabIndicatorImg[i], mTabTitle[i])));
		}

		mTabLayout.addOnTabSelectedListener (this);
		mViewPager.addOnPageChangeListener (this);

	}

	private View getTabItemCustonView(int drawableId, String title) {
		View rootView = LayoutInflater.from (this).inflate (R.layout.tablayout_img_tv, null);
		ImageView img = (ImageView) rootView.findViewById (R.id.tab_img);
		TextView tv = (TextView) rootView.findViewById (R.id.tab_tv);
		img.setImageResource (drawableId);
		tv.setText (title);
		return rootView;
	}

	private class HomePagerFragmentAdapter extends FragmentPagerAdapter {

		public HomePagerFragmentAdapter(FragmentManager fm) {
			super (fm);
		}

		@Override
		public Fragment getItem(int position) {

			switch (position) {
				case 0:
//					return new HomepageFragment ();
					return new TabHomeFragment();
				case 1:
					return new NearbyFragment ();
				case 2:
					return new UserFragment ();
				default:
					return new TabHomeFragment ();

			}
		}

		@Override
		public int getCount() {
			return mTabTitle.length;
		}
	}

	//  -----TabLayout  切换监听
	@Override
	public void onTabSelected(TabLayout.Tab tab) {
		mViewPager.setCurrentItem (tab.getPosition (), false);
	}

	@Override
	public void onTabUnselected(TabLayout.Tab tab) {

	}

	@Override
	public void onTabReselected(TabLayout.Tab tab) {

	}

	//   -----------------ViewPager切换监听----------

	private int mPreviousScrollState;
	private int mScrollState;

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		if (mTabLayout != null) {
			final boolean updateText = (mScrollState == ViewPager.SCROLL_STATE_DRAGGING)
					|| (mScrollState == ViewPager.SCROLL_STATE_SETTLING
					&& mPreviousScrollState == ViewPager.SCROLL_STATE_DRAGGING
			);
			mTabLayout.setScrollPosition (position, positionOffset, updateText);
		}
	}

	@Override
	public void onPageSelected(int position) {

	}

	@Override
	public void onPageScrollStateChanged(int state) {
		mPreviousScrollState = mScrollState;
		mScrollState = state;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		super.onSaveInstanceState (outState);
	}


	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@AfterPermissionGranted(READ_AND_WRITE_STORE)
	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
		if (EasyPermissions.hasPermissions (this, perms)) {
			// Already have permission, do the thing
			// ...
			Log.e ("MainActivity", "已经获得读写本地文件的权限");
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "需要读取本地文件权限",
					READ_AND_WRITE_STORE, perms);
		}
	}
	private final String[] BASIC_PERMISSIONS = new String[]{
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.CAMERA,
//			Manifest.permission.READ_PHONE_STATE,
			Manifest.permission.RECORD_AUDIO,
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION
	};
}
